package com.ruan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruan.common.Code;
import com.ruan.common.R;
import com.ruan.common.Result;
import com.ruan.mapper.DepartLocationMapper;
import com.ruan.mapper.DepartmentMapper;
import com.ruan.mapper.EmployeeMapper;
import com.ruan.pojo.*;
import com.ruan.pojoExt.DepartmentExt;
import com.ruan.service.DepartLocationService;
import com.ruan.service.DepartmentService;

import com.ruan.service.EmployeeService;
import com.ruan.service.PositionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin//在浏览器中从一个源网站向另一个不同源的网站发起请求。为了增加安全性，浏览器通常会阻止跨域请求。为了允许跨域请求，可以在Spring控制器的方法上添加@CrossOrigin注解。
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    DepartmentMapper departmentMapper;

    @Autowired
    private DepartLocationService departLocationService;

    @Autowired
    private DepartLocationMapper departLocationMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    PositionService positionService;

     /**
     * 查询全部部门信息
     */
     @PostMapping("/getAllDepartment/{currentPage}/{pageSize}")
    public Result getAllDepartment(@PathVariable int currentPage,
                            @PathVariable int pageSize) {//@RequestParam(defaultValue = "1") Interger currentPage,
                                                        //@RequestParam(defaultValue = "10") Interger pageSize
//         System.out.println("getAllDepartment传来的参数是："+currentPage+pageSize);
         Page<Department> iPage=new Page<>(currentPage,pageSize);
         LambdaQueryWrapper<Department> departmentWrapper =new LambdaQueryWrapper<>();
         //需要用户名字模糊搜索吗。。。。
         Page<DepartmentExt> iPageExt=new Page<>();//封装
         //调用departmentService.page(iPage, departmentWrapper);后没有明确的返回值，可能有以下几种情况：
         //-------------------------
         //page方法内部进行了数据库查询操作，并将查询结果存储在iPage对象中，但没有显式返回结果。在这种情况下，通过iPage对象可以获取到查询结果。
         //page方法内部对数据库进行了更新操作或其他操作，不需要返回具体结果。
         //在调用page方法后可能会进行其他操作，比如对查询结果进行进一步处理或展示，而不需要返回值。
         //总的来说，即使没有明确的返回值，调用departmentService.page(iPage, departmentWrapper);
         //仍然可以起效，只是需要根据具体情况来处理查询结果或后续逻辑
         departmentService.page(iPage,departmentWrapper);//page方法已经已经继承了IService,
         // 已经提供了分页查询方法，只需要把Page对象和queryWrapper对象构造好，传给他，自己就会进行分页查询
         BeanUtils.copyProperties(iPage,iPageExt,"records");//从iPage一个一个拷贝属性到iPageExt上(除了records)
         List<Department> records = iPage.getRecords();
         List<DepartmentExt> list = records.stream().map((item) -> {//item:遍历出来的每一个部门对象
             DepartmentExt departmentExt = new DepartmentExt();//只有departmentExt符合项目管理页面的要求，所以new一个出来,进行填充
             BeanUtils.copyProperties(item,departmentExt);//先填充入Resign的普通属性

             Long employeeId = item.getEmployeeId();//部门经理的id

//             Employee employee = employeeService.getById(employeeId);
             LambdaQueryWrapper<Employee> employeeQueryWrapper = new LambdaQueryWrapper();
             employeeQueryWrapper.eq(Employee::getId,employeeId);
             employeeQueryWrapper.notIn(Employee::getStatus,"待审核","离职");
             Employee employee = employeeMapper.selectOne(employeeQueryWrapper);

             System.out.println("item.getName()是"+item.getName());

             if("总部".equals(item.getName())){//字符串比较应该使用equals方法而不是==操作符
                 System.out.println("找总经理");
                 LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
                 queryWrapper.eq(Employee::getPositionId,9);//既是总经理，也是总部的部门经理
                 queryWrapper.notIn(Employee::getStatus,"待审核","离职");
                 Employee employee1 = employeeMapper.selectOne(queryWrapper);
                 if(employee1!=null){
//                     System.out.println("找到总经理了"+employee1);
                     item.setEmployeeId(employee1.getId());
                     item.setPhone(employee1.getPhone());
                     departmentMapper.updateById(item);
                     departmentExt.setEmployeeName(employee1.getName());
                 }
             }
//             else{
//                 System.out.println("找其它部门纠正数据");
//                 LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
//                 queryWrapper.ne(Employee::getPositionId,9)
//                         .notIn(Employee::getStatus,"待审核","离职");
//                 List<Employee> employeeList = employeeMapper.selectList(queryWrapper);
//                 System.out.println("employeeList是"+employeeList);
//                 for(Employee employee1 : employeeList){
//                     Position position = positionService.getById(employee1.getPositionId());
//                     if(position!=null) {
//                         if (position.getPname().equals("部门经理")) {
//                             System.out.println("找到一个部门经理："+position.getPname() + "他是谁："+employee1.getName());
//                             Department department = departmentService.getById(employee1.getDepartmentId());
//                             department.setEmployeeId(employee1.getId());
//                             departmentMapper.updateById(department);
//                         }
//                     }
//                 }
//             }
//             System.out.println("employee是null吗："+employee);
             LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
             queryWrapper.eq(Employee::getDepartmentId,item.getId());
             queryWrapper.notIn(Employee::getStatus,"待审核","离职");
             List<Employee> employeeList = employeeMapper.selectList(queryWrapper);
             System.out.println(item.getName()+"部门有多少人："+employeeList.size());
             item.setNumber(employeeList.size());
             departmentMapper.updateById(item);//纠正部门的人数
             departmentExt.setNumber(employeeList.size());
             if(employee != null){//员工表能查到相应的员工(理应是部门经理)

                 //无论有没有部门经理，都要更新部门人数，所以要移出去
//                 LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
//                 queryWrapper.eq(Employee::getDepartmentId,item.getId());
//                 queryWrapper.notIn(Employee::getStatus,"待审核","离职");
//                 List<Employee> employeeList = employeeMapper.selectList(queryWrapper);
//                 System.out.println(item.getName()+"部门有多少人："+employeeList.size());
//                 item.setNumber(employeeList.size());
//                 departmentMapper.updateById(item);//纠正部门的人数
//                 departmentExt.setNumber(employeeList.size());

                 departmentExt.setEmployeeName(employee.getName());//填充入employee没有的employeeName属性
                 System.out.println(item.getName()+"部门有手机号了吗："+item.getPhone());
                 if(item.getPhone()==null || item.getPhone().equals("暂无")){
                     item.setPhone(employee.getPhone());
                     departmentMapper.updateById(item);//纠正(填充)这个部门的联系方式
                     departmentExt.setPhone(employee.getPhone());
                 }

                 //查一查这个人现在的当前部门和职位是什么，如果不是部门经理，说明是残留的数据，以前可能是部门经理
//                 Position position1 = positionService.getById(employee.getPositionId());
//                 Department department = departmentService.getById(employee.getDepartmentId());
//                 System.out.println("这个人是什么部门的："+department.getName()+"当前遍历的部门是："+item.getName());
//                 if(!position1.getPname().equals("部门经理") || !department.getName().equals(item.getName())){
//                     System.out.println("员工表查到的不是部门经理"+"或者部门不匹配");
//
//                     Department department1 = departmentService.lambdaQuery().eq(Department::getId,item.getId()).one();
//                     if(department1!=null){
//                         System.out.println("department1是"+department1);
//                         departmentService.update(new UpdateWrapper<Department>().lambda()
//                                 .set(Department::getPhone,"暂无")
//                                 .set(Department::getEmployeeId,null)
//                                 .eq(Department::getId,department1.getId()));
//                         System.out.println("department1更新后"+departmentService.getById(item.getId()));
//                     }
//
//                     departmentExt.setEmployeeName(null);//确定了这个人不是该部门的部门经理
//                 }

//                 employee.setDepartmentId(item.getId());//部门经理一定是属于这个部门的
//                 employee.setPositionId(Long.valueOf(1));//部门经理的id是1
//                 employeeMapper.updateById(employee);//纠正这个部门经理的归属
                 Position position = positionService.getById(employee.getPositionId());
                 if(position != null) {
                     departmentExt.setPosition(position.getPname());
                 }
             }else{//找不到部门经理，联系方式应该是空的
                 departmentExt.setPhone(null);
             }

//             LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
//             queryWrapper.eq(Employee::getDepartmentId,item.getId());
//             queryWrapper.notIn(Employee::getStatus,"待审核","离职");
//             List<Employee> employeeList = employeeMapper.selectList(queryWrapper);
//             System.out.println(item.getName()+"部门有多少人："+employeeList.size());
//             item.setNumber(employeeList.size());
//             departmentMapper.updateById(item);//纠正部门的人数
//             departmentExt.setNumber(employeeList.size());

             return departmentExt;//填充完新键的employeeExt之后，返回，把遍历的这些employeeExt对象搜集起来后
         }).collect(Collectors.toList());//就转成集合了，赋给List<EmployeeExt> list
         System.out.println("getAllDepartment的list里有了什么"+list);//.toString()
         iPageExt.setRecords(list);

         return new Result(Code.SELECT_OK,iPageExt);
    }

    //部门名独一无二验证
    @GetMapping("/checkUniqueDepartmentName")
    public boolean checkUniqueDepartmentName(@RequestParam String departmentName) {
        System.out.println("checkUniqueDepartmentName能生效吗"+departmentName);
        LambdaQueryWrapper<Department> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Department::getName, departmentName);
        return departmentMapper.selectCount(queryWrapper) == 0;
    }

    @GetMapping("/showAddButton/{departmentId}")
    public Result showAddButton(@PathVariable Long departmentId){
        System.out.println("showAddButton传的参数是："+departmentId);
        LambdaQueryWrapper<DepartLocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DepartLocation::getDepartmentId, departmentId);
        List<DepartLocation> departLocationList = departLocationMapper.selectList(queryWrapper);
        System.out.println("departLocationList是null还是''"+departLocationList);
        if (departLocationList.isEmpty()){
            System.out.println("departLocationList是Empty");
            return new Result(Code.SELECT_ERR,"");
        }
        System.out.println("departLocationList不是null");
        return new Result(Code.SELECT_OK,"");
    }

    /**
     * 添加部门定位信息
     */
    @PostMapping("/addDepartmentLocation")
    public Result addDepartmentLocation(@RequestParam Long departmentId,
                                           @RequestBody DepartLocation location) {
        // 获取前端发送的新的经纬信息Double.valueOf(
        Double newLatitude = Double.valueOf(location.getLatitude());
        Double newLongitude = Double.valueOf(location.getLongitude());


        // 根据部门ID添加部门的经纬信息
        boolean a = departLocationService.addDepartmentLocation(departmentId,
                newLatitude, newLongitude);
        if(a){
            return new Result(Code.SAVE_OK,"部门定位信息已添加");
        }
        return new Result(Code.SAVE_ERR,"部门定位信息添加失败！");
    }

    /**
     * 更新部门定位信息
     */
    @PostMapping("/updateDepartmentLocation")
    public Result updateDepartmentLocation(@RequestParam Long departmentId,
                                           @RequestBody DepartLocation location) {
        // 获取前端发送的新的经纬信息Double.valueOf(
        Double newLatitude = Double.valueOf(location.getLatitude());
        Double newLongitude = Double.valueOf(location.getLongitude());


        // 根据部门ID更新部门的经纬信息
        boolean a = departLocationService.updateDepartmentLocation(departmentId,
                newLatitude, newLongitude);
        if(a){
            return new Result(Code.UPDATE_OK,"部门定位信息已更新");
        }
        return new Result(Code.UPDATE_ERR,"部门定位信息更新失败！");
    }

    @PostMapping("/updateDepartment")
    public Result updateDepartment(@RequestBody Department department){
        System.out.println("更新部门参数："+department);
        //先清空这个部门以前的部门经理的部门信息，全部贬为员工
        Department department1 = departmentService.getById(department.getId());
        if(department1!=null){
            Employee employeeOld = employeeService.getById(department1.getEmployeeId());
//        if(employeeOld.getPositionId().equals(1)){//如果该部门已经有了部门经理
//            return new Result(Code.UPDATE_ERR,"该部门的部门经理已存在！");
//        }
          if(employeeOld!=null){
              employeeOld.setPositionId(5L);//全部贬为员工
              //        employeeOld.setDepartmentId();//留在本部门
              employeeMapper.updateById(employeeOld);
          }
        }


        Employee employee = employeeService.getById(department.getEmployeeId());
        employee.setPositionId(Long.valueOf(1));//更新员工的职位
        employee.setDepartmentId(department.getId());//更新员工的所在部门
        //        employee.setPosition("部门经理");
        System.out.println("employee是："+employee);
        employeeMapper.updateById(employee);//更新到数据库
        //     初始设置部门主管的phone作为部门的phonedepartment.getPhone() == null ||
        if(department.getPhone().isBlank()){
            //isBlank()方法更严格，它不仅检查字符串是否为空，还会检查字符串是否只包含空格。
            // 而isEmpty()方法只检查字符串是否为空或者为null。
            System.out.println("Phone是" + department.getPhone());
            department.setPhone(employee.getPhone());
        }

        System.out.println("department是："+department);
        if (departmentService.updateById(department)){
            return new Result(Code.UPDATE_OK,"修改成功！");
        }
        return new Result(Code.UPDATE_ERR,"修改失败！");
    }

    @GetMapping("/stopDepart/{id}")
    public Result stopDepart(@PathVariable Long id){

        if (departmentService.stopDepart(id)){
            return new Result(Code.UPDATE_OK,"禁用成功！");
        }else {
            return new Result(Code.UPDATE_ERR,"禁用失败，请检查当前部门下是否存在员工！");
        }
    }

    @DeleteMapping("/deleteDepart/{id}")
    public Result deleteDepart(@PathVariable Long id){
        try {
            return departmentService.deleteDepart(id);
//            return new Result(Code.DELETE_OK,"删除部门成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.DELETE_ERR,"删除部门失败！");
        }
    }

    @GetMapping("/startDepart/{id}")
    public Result startDepart(@PathVariable Long id){

        if (departmentService.startDepart(id)){
            return new Result(Code.UPDATE_OK,"启用成功！");
        }else {
            return new Result(Code.UPDATE_ERR,"启用失败！");
        }
    }

    @PostMapping("/addDepart")
    public Result addDepart(@RequestBody Department department){
        if (departmentService.addDepart(department)){
            return new Result(Code.SAVE_OK,"添加成功！");
        }else {
            return new Result(Code.SAVE_ERR,"添加失败，请检查当前部门是否存在！");
        }
    }

    @GetMapping("/getDepart")
    public Result getDepart(){
        try {
            List<Department> departmentList = departmentService.getDepart();
            System.out.println("查看部门信息："+departmentList);
            return new Result(Code.SELECT_OK,departmentList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.SELECT_ERR,"查询部门失败！");
        }

    }

}
